from asyncio.windows_events import NULL
from calendar import c
from re import M
from flask_restful import Resource, reqparse
from flask import request
from models import db, Dish
from utils import api_response
import logging

# 配置日志
logger = logging.getLogger(__name__)

class DishList(Resource):
    def get(self):
        """获取菜品列表"""
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('category_id', type=int, location='args')
            parser.add_argument('status', type=int, location='args')
            parser.add_argument('page', type=int, default=1, location='args')
            parser.add_argument('size', type=int, default=10, location='args')
            args = parser.parse_args()
                        
            query = Dish.query
            if args['category_id'] is not None:
                query = query.filter_by(category_id=args['category_id'])
            if args['status'] is not None:
                query = query.filter_by(status=args['status'])
            
            dishes = query.paginate(
                page=args['page'], 
                per_page=args['size'], 
                error_out=False
            )
            
            return api_response({
                'total': dishes.total,
                'page': args['page'],
                'size': args['size'],
                'dishes': [dish.to_dict() for dish in dishes.items]
            })
    
        except Exception as e:
            logger.error(f"Error in DishList.get: {str(e)}")
            import traceback
            logger.error(f"Traceback: {traceback.format_exc()}")
            return api_response(None, f"获取菜品列表失败: {str(e)}", 500)
    
    def post(self):
        """创建菜品"""
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('category_id', type=int, required=True, help='分类ID不能为空')
            parser.add_argument('name', type=str, required=True, help='菜品名称不能为空')
            parser.add_argument('description', type=str)
            parser.add_argument('price', type=float, required=True, help='价格不能为空')
            parser.add_argument('image_url', type=str)
            parser.add_argument('sales', type=int, default=0)
            parser.add_argument('status', type=int, default=1)
            parser.add_argument('sort_order', type=int, default=0)
            args = parser.parse_args()
            
            dish = Dish(
                category_id=args['category_id'],
                name=args['name'],
                description=args['description'],
                price=args['price'],
                image_url=args['image_url'],
                sales=args['sales'],
                status=args['status'],
                sort_order=args['sort_order']
            )
            
            db.session.add(dish)
            db.session.commit()
            
            return api_response(dish.to_dict(), message='菜品创建成功')
        except Exception as e:
            logger.error(f"Error in DishList.post: {str(e)}")
            db.session.rollback()
            return api_response(None, f"创建菜品失败: {str(e)}", 500)

class DishDetail(Resource):
    def get(self, dish_id):
        """获取菜品详情"""
        try:
            dish = Dish.query.get(dish_id)
            if not dish:
                return api_response({'message': '菜品不存在'}, code=404)
            
            return api_response(dish.to_dict())
        except Exception as e:
            logger.error(f"Error in DishDetail.get: {str(e)}")
            return api_response(None, f"获取菜品详情失败: {str(e)}", 500)
    
    def put(self, dish_id):
        """更新菜品"""
        try:
            dish = Dish.query.get(dish_id)
            if not dish:
                return api_response({'message': '菜品不存在'}, code=404)
            
            parser = reqparse.RequestParser()
            parser.add_argument('category_id', type=int)
            parser.add_argument('name', type=str)
            parser.add_argument('description', type=str)
            parser.add_argument('price', type=float)
            parser.add_argument('image_url', type=str)
            parser.add_argument('sales', type=int)
            parser.add_argument('status', type=int)
            parser.add_argument('sort_order', type=int)
            args = parser.parse_args()
            
            if args['category_id'] is not None:
                dish.category_id = args['category_id']
            if args['name'] is not None:
                dish.name = args['name']
            if args['description'] is not None:
                dish.description = args['description']
            if args['price'] is not None:
                dish.price = args['price']
            if args['image_url'] is not None:
                dish.image_url = args['image_url']
            if args['sales'] is not None:
                dish.sales = args['sales']
            if args['status'] is not None:
                dish.status = args['status']
            if args['sort_order'] is not None:
                dish.sort_order = args['sort_order']
            
            db.session.commit()
            
            return api_response(dish.to_dict(), message='菜品更新成功')
        except Exception as e:
            logger.error(f"Error in DishDetail.put: {str(e)}")
            db.session.rollback()
            return api_response(None, f"更新菜品失败: {str(e)}", 500)
    
    def delete(self, dish_id):
        """删除菜品"""
        try:
            dish = Dish.query.get(dish_id)
            if not dish:
                return api_response({'message': '菜品不存在'}, code=404)
            
            db.session.delete(dish)
            db.session.commit()
            
            return api_response(None, message='菜品删除成功')
        except Exception as e:
            logger.error(f"Error in DishDetail.delete: {str(e)}")
            db.session.rollback()
            return api_response(None, f"删除菜品失败: {str(e)}", 500)